#include <iostream>
#include "Sieve.h"
#include "SwapVector.h"

using namespace std;

SieveImp::SieveImp(int _max, EventProcessor& _filter)

#ifdef DEBUG_EVPROC
, EventProcessorImp(true,"Sieve") // comment to remove debug
#endif
{
	Filter.CopyFrom(_filter);
	max = _max;
	RegisterMessageProcessor(DieMessage::type, &Die, 0 /*priority*/);
	RegisterMessageProcessor(DoneMessage::type, &Done, 1 /*priority*/);
	Initialize();	
}

void SieveImp::SendStream(){

	cout<<"Vector size before sending the message "<<swapVector.vec.size()<<endl;
	cout.flush();

	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface); 
	FilterMessage_Factory(Filter, currentPrime , swapVector,myInterfClone);

	cout<<"Vector size after sending the message "<<swapVector.vec.size()<<endl;
	cout.flush();


}
void SieveImp::Initialize(){

	currentPrime = 2;
	primes.push_back(currentPrime);
	for(int i = 2; i <= max; ++i){
		swapVector.vec.push_back(i);
	}

	SendStream();
}
MESSAGE_HANDLER_DEFINITION_BEGIN(SieveImp, Done, DoneMessage)

	evProc.currentPrime = msg.stream.vec.at(0);
	evProc.primes.push_back(evProc.currentPrime);

	msg.stream.vec.erase(msg.stream.vec.begin());	
	evProc.swapVector.vec.swap(msg.stream.vec);
	int p = evProc.currentPrime;

	if(p*p > evProc.max){
		KillEvProc(msg.sender);
		evProc.Seppuku();
		vector<int>::iterator xit;
		for(xit = evProc.swapVector.vec.begin(); xit != evProc.swapVector.vec.end();++xit){
			evProc.primes.push_back(*xit);
		}
	}
	else{
		evProc.SendStream();
	}	

MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(SieveImp, Die, DieMessage)

	cout<<"The primes are "<<endl;
	vector<int>::iterator xit;
	for(xit = evProc.primes.begin(); xit != evProc.primes.end();++xit){
		cout<<*xit<<" ";		

	}	
	cout<<"\nKilling the Sieve "<<endl;
	evProc.EventProcessorImp::processDieMessage(evProc, msg);

MESSAGE_HANDLER_DEFINITION_END
